package sicnu.cs.aps.security.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import sicnu.cs.aps.security.token.EmailAuthenticationToken;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author CaiKe
 * @date 2021/11/10 17:42
 */
@Slf4j
public class EmailAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private final ObjectMapper objectMapper;

    /**
     * form中的邮箱字段
     */
    public static final String SECURITY_FORM_EMAIL_KEY = "email";
    public static final String SECURITY_FORM_CODE_KEY = "code";

    private String emailParam = SECURITY_FORM_EMAIL_KEY;
    private String codeParam = SECURITY_FORM_CODE_KEY;

    private boolean postOnly = true;

    @Override
    public void setFilterProcessesUrl(String filterProcessesUrl) {
        super.setFilterProcessesUrl(filterProcessesUrl);
    }


    public EmailAuthenticationFilter(ObjectMapper objectMapper) {
        super(new AntPathRequestMatcher("/email/login", "POST"));
        this.objectMapper = objectMapper;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (postOnly && !"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        var map = obtainInfo(request);
        var email = map.get(emailParam);
        var code = map.get(codeParam);
        if (email == null) {
            email = "";
        }
        email = email.trim();
        final EmailAuthenticationToken token = new EmailAuthenticationToken(email, code);
        setDetails(request, token);
        return this.getAuthenticationManager().authenticate(token);
    }

    protected Map<String, String> obtainInfo(HttpServletRequest request) {
        try (InputStream in = request.getInputStream()) {
            var jsonNode = objectMapper.readTree(in);
            if (!jsonNode.has(emailParam) || !jsonNode.has(codeParam)) {
                throw new BadCredentialsException("参数不正确！");
            }
            final String email = jsonNode.get(emailParam).textValue();
            final String code = jsonNode.get(codeParam).textValue();
            return Map.of(
                    "email", email,
                    "code", code);
        } catch (IOException e) {
            throw new BadCredentialsException("JSON解析错误");
        }
    }

    protected void setDetails(HttpServletRequest request, EmailAuthenticationToken token) {
        token.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setEmailParam(String emailParam) {
        this.emailParam = emailParam;
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }
}